package com.pjb.springbootjjwt.store.entity;

import com.pjb.springbootjjwt.store.storage.DDL;
import com.pjb.springbootjjwt.store.utils.FileUtil;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.IOException;
import java.util.List;

@Data
@AllArgsConstructor
public class Response {

    public static Response success = new Response("0000", "success", "");
    public static Response error = new Response("9999", "error", "");

    private String code;
    private String msg;
    private String data;

    public static void printQuery(Record record, String sql) throws IOException {
        Response res = Response.success.set(FileUtil.jsonStr(record.getLine()));
        System.out.println(res.getCode() + "," + res.getMsg() + ",\t" + sql);
        System.out.println();
        System.out.println("----------------------------------------------------");
        printLine(record.getHead().getData());
        System.out.println("----------------------------------------------------");
        String name = (new DDL()).showStatus("");
        for (Line line : record.getLine()) {
            printLine(line.getData());
            if (!sql.contains("select"))
                writeLine(name, line.getData());
        }
//        System.out.println("----------------------------------------------------");
    }

    private static void printLine(List<String> data) {
        StringBuilder c = new StringBuilder();
        for (String s : data) {
            c.append(s).append("\t\t");
        }
        System.out.println(c);
    }

    private static void writeLine(String file, List<String> data) {
        StringBuilder c = new StringBuilder();
        c.append(System.currentTimeMillis()).append(":\t");
        for (String s : data) {
            c.append(s).append("\t\t");
        }
        c.append("\r\n");

        try {
            FileUtil.append(file, c.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Response set(String data) {
        this.data = data;
        return this;
    }

    public Response set(String msg, String data) {
        msg = String.format(msg, data);
        this.code = msg.substring(msg.indexOf("sqlstate"), msg.indexOf(".")).replaceAll("sqlstate", "").trim();
        this.msg = msg;
        this.data = data;
        return this;
    }
}
